//
//  FirCirBgImagedb.m
//  tcpoctest
//
//  Created by apple on 13-5-3.
//  Copyright (c) 2013年 gump. All rights reserved.
//

#import "FirCirBgImagedb.h"
#import "FirCirBgImageDataSource.h"

@implementation FirCirBgImagedb

-(void)creatTable
{
    if (db == nil) {
        return;
    }
    
    pthread_mutex_lock(&mutexdatabase);
    
    [db open];
    [db executeUpdate:@"create table if not exists fcbgimage(mail text primary key,imageurl text)"];
    [db close];
    
    pthread_mutex_unlock(&mutexdatabase);
}

-(void)insertBgImageUrl:(NSString *)mail withURL:(NSString *)url
{
    if (db == nil) {
        return;
    }
    
    NSString *strsql = [NSString stringWithFormat:@"SELECT imageurl FROM fcbgimage WHERE mail = '%@'",mail];
    
    pthread_mutex_lock(&mutexdatabase);
    
    [db open];
    
    FMResultSet *s = [db executeQuery:strsql];
    if([s next])
    {
        strsql = [NSString stringWithFormat:@"update fcbgimage set imageurl = '%@' WHERE mail = '%@'",
                  url,
                  mail];
    }
    else
    {
        strsql = [NSString stringWithFormat:@"insert into fcbgimage(mail,imageurl) values('%@','%@')",
                  mail,
                  url];
    }
    
    [db executeUpdate:strsql];
    [db close];
    
    pthread_mutex_unlock(&mutexdatabase);
}

-(void)deleteBgImageByMail:(NSString *)mail
{
    if (db == nil) {
        return;
    }
    
    NSString *strsql = [NSString stringWithFormat:@"DELETE FROM fcbgimage WHERE mail='%@'"
                        ,mail];
    
    pthread_mutex_lock(&mutexdatabase);
    
    [db open];
    [db executeUpdate:strsql];
    [db close];
    
    pthread_mutex_unlock(&mutexdatabase);
}

-(void)initData
{
    if (db == nil) {
        return;
    }
    
    pthread_mutex_lock(&mutexdatabase);
    
    [db open];
    
    NSString *strsql = [NSString stringWithFormat:@"SELECT * FROM fcbgimage"];
    FMResultSet *s = [db executeQuery:strsql];
    
    [[DataControl shareControl].fcBgImageDS RemoveAll];
    
    while ([s next])
    {
        [[DataControl shareControl].fcBgImageDS AddImagePath:[s stringForColumn:@"imageurl"]
                                                    withMail:[s stringForColumn:@"mail"]];
    }
    
    [db close];
    
    pthread_mutex_unlock(&mutexdatabase);
}

@end
